package com.loto.webapp.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.loto.webapp.common.PageResultSet;
import com.loto.webapp.common.Pager;
import com.loto.webapp.dao.BaseDao;

public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {

	public PageResultSet<Object> queryByPage(String hql, int pageSize,
			int pageIndex) {
		int totalRow = queryRowCount(hql);

		Pager pager = new Pager(totalRow, pageSize, pageIndex);

		List<Object> list = queryByPager(hql, pager.getBeginIndex(),
				pager.getPageSize());

		PageResultSet<Object> pageResultSet = new PageResultSet<Object>();

		pageResultSet.setList(list);

		pageResultSet.setPager(pager);

		return pageResultSet;
	}

	private List<Object> queryByPager(String hql, int beginIndex, int pageSize) {
		Session session = getSessionFactory().getCurrentSession();
		Transaction trans = null;
		try {
			trans = session.beginTransaction();

			Query query = session.createQuery(hql);
			query.setFirstResult(beginIndex);
			query.setMaxResults(pageSize);
			List<Object> list = query.list();

			session.getTransaction().commit();
			return list;
		} catch (Exception e) {
			if (null != trans) {
				trans.rollback();
				e.printStackTrace();
			}
		}
		return null;
	}

	private int queryRowCount(String hql) {
		Session session = getSessionFactory().getCurrentSession();
		Transaction trans = null;
		try {
			trans = session.beginTransaction();

			Query query = session.createQuery(hql);
			int result = query.list().size();

			session.getTransaction().commit();
			return result;
		} catch (Exception e) {
			if (null != trans) {
				trans.rollback();
				e.printStackTrace();
			}
		}
		return 0;
	}

}
